import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {HttpResponse} from '@angular/common/http';
import {tap} from 'rxjs/operators';
import {Router} from '@angular/router';
import {HttpErrorResponse} from '@angular/common/http';
import {AlertComponent} from "./alert";

// 拦截器
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    showNotification: boolean;
    timer: number;

    constructor(
        private router: Router,
        private alertComponent: AlertComponent,
    ) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('medicalToken'); // token保存在localstorage
        if (token) { // 如果有token，就添加
            req = req.clone({
                setHeaders: {
                    'X-Auth-Token': token,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
        } else {
            req = req.clone({
                setHeaders: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
        }
        return next.handle(req).pipe(
            tap(event => {
                if (event instanceof HttpResponse) { // 这里是返回，可通过event.body获取返回内容
                }
            }, error => { // 统一处理所有的http错误
                if (error instanceof HttpErrorResponse) {
                    if (error.status === 401) {
                        localStorage.setItem('userName', '');
                        this.router.navigate(['/login']).then();
                        this.openNotification('请重新登录');
                    }
                }
            })
        );
    }

    openNotification(error) {
        if (!this.showNotification) {
            this.showNotification = true;
            // @ts-ignore
            this.timer = setTimeout(() => {
                this.showNotification = false;
            }, 5000);
            this.alertComponent.presentAlert(error).then();
        }
    }
}
